package com.baoxin.chenxixc4coach;

import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.baoxin.chenxixc4coach.adapter.UnckechAdapter;
import com.baoxin.chenxixc4coach.bean.UncheckStudent;
import com.baoxin.chenxixc4coach.java.MyHandler;
import com.baoxin.chenxixc4coach.java.SimpleResultHelper;
import com.baoxin.chenxixc4coach.utils.Interfaces;
import com.baoxin.chenxixc4coach.utils.Msg;
import com.baoxin.chenxixc4coach.utils.NetUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static android.support.v7.widget.RecyclerView.SCROLL_STATE_IDLE;

public class UncheckedStudentActivity extends BaseActivity implements UnckechAdapter.CheckListener {

    private RecyclerView mRecyclerView;
    private Handler handler;
    private List<UncheckStudent> uncheckStudents;
    private UnckechAdapter adapter;
    private int limit = 10;
    private int currentPage = 1;
    private int lastVisibleItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unchecked_student);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mRecyclerView = findViewById(R.id.recyclerview);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        adapter = new UnckechAdapter(this, this);
        mRecyclerView.setAdapter(adapter);

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == SCROLL_STATE_IDLE && lastVisibleItem == uncheckStudents.size()) {
                    updateData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });

        handler = new MyHandler(this, activity) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case Msg.REQUEST_SUCCEED:
                        ArrayList<UncheckStudent> newStudents = (ArrayList) msg.obj;
                        for (UncheckStudent o : newStudents) {
                            uncheckStudents.add(o);
                        }
                        adapter.updateData(uncheckStudents, newStudents.size() == 0 ? false : true);
                        break;
                }
            }
        };

        updateData();
    }

    private void updateData() {
        if (uncheckStudents == null) {
            uncheckStudents = new ArrayList<>();
        }
        JSONObject body = new JSONObject();
        try {
            body.put("page", currentPage);
            body.put("limit", limit);
            NetUtil.post(this, Interfaces.URL_UNCHECK_STUDENTS, body.toString(), new MyCallback(Interfaces.URL_UNCHECK_STUDENTS, handler));
        } catch (Exception e) {
            e.printStackTrace();
        }
        currentPage++;
    }

    @Override
    public void onPass(int position) {
        final UncheckStudent student = uncheckStudents.get(position);

        JSONObject body = new JSONObject();
        try {
            body.put("userId", student.getUserId());
            body.put("checkRes", 1);
            body.put("octId", student.getOctId());
            NetUtil.post(this, Interfaces.URL_CHECK_STUDENT, body.toString(), new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String result = response.body().string();
                    if (SimpleResultHelper.isSucceed(result)) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                student.setCheckState(1);
                                adapter.notifyDataSetChanged();
                            }
                        });
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onRefuse(int position) {
        final UncheckStudent student = uncheckStudents.get(position);
        JSONObject body = new JSONObject();
        try {
            body.put("userId", student.getUserId());
            body.put("checkRes", 2);
            body.put("octId", student.getOctId());
            NetUtil.post(this, Interfaces.URL_CHECK_STUDENT, body.toString(), new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String result = response.body().string();
                    if (SimpleResultHelper.isSucceed(result)) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                student.setCheckState(2);
                                adapter.notifyDataSetChanged();
                            }
                        });
                    }

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void doCheck(int passTag) {

    }
}
